package com.singlemountaintech.haogongjiang.http.interceptor;

import android.content.Context;
import android.util.Log;

import com.google.gson.Gson;
import com.singlemountaintech.haogongjiang.model.Error;
import com.singlemountaintech.haogongjiang.qfd.constant.Keys;
import com.singlemountaintech.haogongjiang.utils.LogUtils;
import com.singlemountaintech.haogongjiang.utils.LoginUtil;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Response;
import rx.Observable;
import rx.functions.Action1;
import rx.functions.Func1;

/**
 * Created by LUOLI on 2016/8/22.
 */
public class ReceivedCookiesInterceptor implements Interceptor {
    private static String TAG = ReceivedCookiesInterceptor.class.getSimpleName();
    private Context context;
    private Gson mGson = new Gson();

    public ReceivedCookiesInterceptor(Context context) {
        super();
        this.context = context;

    }

    @Override
    public Response intercept(final Chain chain) throws IOException {

        Response originalResponse = chain.proceed(chain.request());
        LogUtils.eNormal(TAG, "url:" + originalResponse.request().url());
        LogUtils.eNormal(TAG, "code:" + originalResponse.code());
        if (originalResponse.code() != 200 && originalResponse.code() != Keys.HTTP_401) {
            String s = originalResponse.body().string();
            Error error = mGson.fromJson(s, Error.class);
            LogUtils.eNormal(TAG, "http code:" + originalResponse.code() + ",error code:" + error.status + ",error message:" + error.message);
            throw new ApiException(error.status, error.message);
        }
        //这里获取请求返回的cookie
        if (!originalResponse.headers("Set-Cookie").isEmpty()) {
            final StringBuffer cookieBuffer = new StringBuffer();
            Observable.from(originalResponse.headers("Set-Cookie"))
                    .map(new Func1<String, String>() {
                        @Override
                        public String call(String s) {
                            String[] cookieArray = s.split(";");
                            return cookieArray[0];
                        }
                    })
                    .subscribe(new Action1<String>() {
                        @Override
                        public void call(String cookie) {
                            cookieBuffer.append(cookie).append(";");
                        }
                    });
            Log.d(TAG, "===服务器的cookie intercept: " + cookieBuffer.toString());

            LoginUtil.putCookie(cookieBuffer.toString());
        }
        return originalResponse;
    }


}
